using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Net;
using System.ComponentModel;
using System.IO;
using MonoTouch.AudioToolbox;
using MonoTouch.AVFoundation;
using System.Xml.Linq;
using MonoTouch.ObjCRuntime;

namespace Hanselminutes
{
	public partial class HomeViewController : UIViewController
	{
		#region Constructors

		public HomeViewController (IntPtr handle) : base(handle)
		{
		}

		[Export("initWithCoder:")]
		public HomeViewController (NSCoder coder) : base(coder)
		{
		}

		public HomeViewController (ShowRepository repo) : base("HomeViewController", null)
		{
			_repo = repo;
		}

		#endregion

		UILoadingView _loadingView;
		ShowRepository _repo;
		TableViewSource _tableSource;

		public override void ViewDidLoad ()
		{
			_tableSource = new TableViewSource (this);
			
			tableView.Source = _tableSource;
		}
		
		public override void ViewDidAppear (bool animated)
		{
			RefreshShowRepo();
		}

		
		/// <summary>
		/// Gets a list of podcasts from local storage or online.
		/// </summary>
		public void RefreshShowRepo ()
		{
			var r = new Reachability ();
			var hasConnection = r.IsHostReachable ("www.hanselminutes.com");
			
			if (hasConnection) {				
				
				var timeSinceLastRefresh = (DateTime.UtcNow - _repo.GetLastRefreshTimeUtc());
				
				if (timeSinceLastRefresh.TotalMinutes < 10) {
					
					Console.WriteLine ("Refreshed podcasts {0} minutes ago, not bothering", timeSinceLastRefresh.TotalMinutes);
					
				}
				else {				
					StartLoadingScreen ("Refreshing shows...");

					Console.WriteLine ("Have connection - get internet version");
					
					UIHelper.StartInternetActivity ();
				
					_repo.Refresh(delegate {
						this.InvokeOnMainThread(delegate {
							StopLoadingScreen ();
							UIHelper.StopInternetActivity ();
							_tableSource.Reload();
						});
					});
				}
			
			} else if (!hasConnection && _repo.HasLocalData) {
			
				Console.WriteLine ("No connection, using local version");
			
			} else {
			
				Console.WriteLine ("No internet - no local version");
				
				using (var alert = new UIAlertView ("Whoops", "You'll need to connect to the internet to get a list of Podcasts", null, "Ok", null)) {
					alert.Dismissed += delegate {
						Console.WriteLine ("Dismissed Alert");
						UIHelper.StopInternetActivity ();
						StopLoadingScreen ();
					};
					alert.Show ();
				}
			}
		}

		void DisplayShow (Show show)
		{
			var player = new PlayerViewController(_repo, show);
			NavigationController.PushViewController(player, true);
		}

		#region UI Helper Methods

		/// <summary>
		/// Creates a Loading Screen with the specified message.
		/// </summary>
		void StartLoadingScreen (string message)
		{
			using (var pool = new NSAutoreleasePool ()) {
				_loadingView = new UILoadingView (message);
				this.View.BringSubviewToFront (_loadingView);
				this.View.AddSubview (_loadingView);
				this.View.UserInteractionEnabled = false;
			}
		}

		/// <summary>
		/// If a loading screen exists, it will fade it out.
		/// </summary>
		void StopLoadingScreen ()
		{
			using (var pool = new NSAutoreleasePool ()) {
				if (_loadingView != null)
					_loadingView.FadeOutAndRemove ();
				this.View.UserInteractionEnabled = true;
			}
		}

		#endregion

		public class TableViewSource : UITableViewSource
		{
			HomeViewController _hvc;
			
			Show[] _podcasts;
			
			public TableViewSource (HomeViewController hvc)
			{
				_hvc = hvc;
				Reload();
			}
			
			public void Reload() {
				var q = from p in _hvc._repo.AllShows
					select p;
				_podcasts = q.ToArray();
				_hvc.tableView.ReloadData();
			}
			
			public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
			{
				string cellIdentifier = "repeatCell";
				
				var cell = tableView.DequeueReusableCell (cellIdentifier);
				if (cell == null) {
					cell = new UITableViewCell (UITableViewCellStyle.Subtitle, cellIdentifier);
				}

				var podcast = _podcasts[indexPath.Row];
				
				//cell.TextLabel.Font = _cellFont;
				cell.TextLabel.Text = podcast.Title;
				cell.DetailTextLabel.Text = podcast.Description;
				
				
				
				if (podcast.OfflineAudioAvailable) {
					cell.Accessory = UITableViewCellAccessory.Checkmark;
				}
				else {
					cell.Accessory = UITableViewCellAccessory.DisclosureIndicator;
				}
				return cell;
			}

			public override int RowsInSection (UITableView tableview, int section)
			{
				return _podcasts.Length;
			}

			public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
			{
				var podcast = _podcasts[indexPath.Row];
				
				Console.WriteLine ("Selected " + podcast.Title);
				
				var r = new Reachability ();
				
				if (podcast.OfflineAudioAvailable) {
					
					_hvc.DisplayShow (podcast);
					
				} else if (r.IsHostReachable ("www.hanselminutes.com")) {
					
					_hvc.DisplayShow (podcast);
					
				} else {
					
					using (var alert = new UIAlertView ("Whoops", "You'll need to be on the internet to do this", null, "Ok", null)) {
						alert.Show ();
					}
					
				}
			}
		}
	}
}
